//
//  JNTAddressBookViewController.m
//  OA
//
//  Created by 王文晓 on 16/8/4.
//  Copyright © 2016年 王文晓. All rights reserved.
//

#import "JNTAddressBookViewController.h"
#import "UserListTableViewCell.h"
#import "UserInfoModel.h"
#import "AddressSelectedToolsView.h"
#import "JNTDataRequestTools.h"
#import "JNTSearchTableViewController.h"
#import "CompanyModel.h"
#import "CompanyContactTableViewCell.h"

@interface JNTAddressBookViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate, UIScrollViewDelegate, UISearchBarDelegate>
@property (nonatomic, strong) NSMutableArray *sectionKeysArray;         //存放所有分区排序后的标题
@property (nonatomic, strong) NSMutableArray *rowArray;
@property (nonatomic, strong) NSMutableDictionary *allModelDic;     //存放model类的联系人
@property (nonatomic, strong) NSMutableDictionary *allDataDic;      //存放所有分区联系人
@property (nonatomic, strong) NSMutableArray *allCompanyArray;
@property (nonatomic, strong) NSMutableArray *topCompanyArray;

@property (nonatomic, strong) UITextField *textFiled;
@property (nonatomic, strong) NSMutableArray *searcherList;
@property (nonatomic, strong) AddressSelectedToolsView *selectedTools;

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIButton *myCompany;
@property (nonatomic, strong) UIScrollView *scrollView;

//@property (nonatomic, strong) UITableView *companyTableView;
@property (nonatomic, assign) BOOL isContactCell;
@end



@implementation JNTAddressBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isContactCell = YES;
    [self requestSuperCompanyData];
    [self initWithTopView];
    
    [self.view addSubview:self.tableView];
    //[self.view addSubview:self.selectedTools];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    //[self.tableView reloadData];
}
//我的单位数据请求
- (void)requestMyCompanyContactData{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"APP*JNT@2015E0298TR",@"authCode", nil];
    NSString *urlString = [NSString stringWithFormat:@"%@/JBaas/user/find/17566", @"http://118.186.223.151:8050"];
    //@"http://192.168.0.180:8050/JBaas/user/find/17566";
    [self fenchDataSourceWithUrlString:urlString parameter:dict];
}
- (void)requestSuperCompanyData{
    NSMutableDictionary *dict1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"APP*JNT@2015E0298TR", @"authCode", @"17566", @"id", nil];
    [self requestSuperCompanyDataWithUrlString:@"http://118.186.223.151:8050/JBaas/unit/findTopParent" parameter:dict1];
}

//搜索框、我的单位、单位筛选
- (void)initWithTopView{
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth * 4 / 5, 35)];
    self.searchBar.barStyle = UISearchBarIconSearch;
    self.searchBar.placeholder = @"姓名、工号、座机、手机";
    self.searchBar.delegate = self;
    [self.view addSubview:self.searchBar];
    
    self.myCompany = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.myCompany setFrame:CGRectMake(kScreenWidth * 4 / 5, 0, kScreenWidth / 5, 35)];
    [self.myCompany setTitle:@"我的公司" forState:UIControlStateNormal];
    [self.myCompany setBackgroundColor:[UIColor colorWithRed:0.1882 green:0.651 blue:0.8863 alpha:1.0]];
    [self.myCompany addTarget:self action:@selector(myCompanyBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.myCompany];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 35, kScreenWidth, 35)];
    self.scrollView.delegate = self;
    self.scrollView.bounces = NO;
    [self.view addSubview:self.scrollView];
}
//scrollView中添加按钮
- (void)initWithButtonInScrollView: (NSMutableArray<CompanyModel *> *)buttonArray{
    CGFloat x = 0;
    for (int i = 0 ; i < buttonArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *buttonTitle = [[NSString alloc] init];
        if (i != 0) {
            buttonTitle = [NSString stringWithFormat:@">%@",buttonArray[i].name];
        } else {
            buttonTitle = buttonArray[i].name;
        }
        CGFloat width = [self getStringWith:buttonTitle];
        [button setFrame:CGRectMake(x, 0, width, 35)];
        [button setTitle:buttonTitle forState:UIControlStateNormal];
        button.tag = buttonArray[i].id;
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button addTarget:self action:@selector(companyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        x = x + width;
        [self.scrollView setContentSize:CGSizeMake(x, 35)];
        [self.scrollView addSubview:button];
    }
}
- (CGFloat)getStringWith:(NSString *)string{
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGSize textSize = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 35) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin  attributes:attributes context:nil].size;
    return textSize.width;
}
//scrollView重新加载按钮
- (void)reloadButtonInScrollView: (NSMutableArray<CompanyModel *> *)array{
    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self initWithButtonInScrollView:array];
}

- (void)companyButtonAction: (UIButton *)sender{
    self.isContactCell = NO;
    NSMutableArray <CompanyModel*>*mutableArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.topCompanyArray.count; i++) {
        CompanyModel *model = (CompanyModel *)self.topCompanyArray[i];
        //NSLog(@"%ld,%ld", sender.tag, model.id);
        if (sender.tag == model.id) {
            for (int j = 0; j <= i; j++){
                [mutableArray addObject:self.topCompanyArray[j]];
            }
        }
    }
    self.topCompanyArray = [[NSMutableArray alloc] init];
    self.topCompanyArray = mutableArray;
    [self reloadButtonInScrollView:self.topCompanyArray];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"APP*JNT@2015E0298TR", @"authCode", [NSString stringWithFormat:@"%ld", sender.tag], @"id", nil];
    [self requestSubCompanyDataWithUrlString:@"http://118.186.223.151:8050/JBaas/unit/findChildById" parameter:dict];
}
//轻拍手势回收键盘
- (void)hideKeyboard:(UITapGestureRecognizer *)sender{
    [self.view endEditing:YES];
}
#pragma mark searchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length != 0) {
        NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithObjectsAndKeys:searchText,@"name",nil];
        [self.allModelDic removeAllObjects];
        [self.sectionKeysArray removeAllObjects];
        [self.tableView reloadData];
        [self fenchDataSourceWithUrlString:AddressBookSearch_URL  parameter:mdic];
    }
}

#pragma mark - --------tableView的代理方法-------
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isContactCell) {
        return self.sectionKeysArray.count;
    } else {
        return 1;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isContactCell) {
        NSString *key = [self.sectionKeysArray objectAtIndex:section];
        NSArray *array = [self.allModelDic objectForKey:key];
        return array.count;
    } else {
        return self.allCompanyArray.count;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isContactCell) {
        UserListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserListCell" forIndexPath:indexPath];
        NSString *key = [self.sectionKeysArray objectAtIndex:indexPath.section];
        NSArray *array = [self.allModelDic objectForKey:key];
        UserInfoModel *model = [array objectAtIndex:indexPath.row];
        cell.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.05];
        [cell setCellWithModel:model];
        //    NSLog(@"model = %@",model.name);
        return cell;

    } else {
        CompanyContactTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CompanyContactTableViewCell" forIndexPath:indexPath];
        CompanyModel *model = self.allCompanyArray[indexPath.row];
        cell.companyName.text = model.name;
        return cell;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.isContactCell) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-30, 30)];
        view.backgroundColor = [UIColor colorWithRed:arc4random()%255/256.0 green:arc4random()%255/256.0 blue:arc4random()%255/256.0 alpha:1.0];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 20, view.frame.size.height-5)];
        label.text = [self.sectionKeysArray objectAtIndex:section];
        [view addSubview:label];
        return view;
    } else {
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.isContactCell) {
        return 30;
    } else {
        return 0;
    }
}
//右边索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.isContactCell) {
        return [self sectionKeysArray];
    } else {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isContactCell) {
        
    } else {
        CompanyModel *model = self.allCompanyArray[indexPath.row];
        [self.topCompanyArray addObject:model];
        [self reloadButtonInScrollView:self.topCompanyArray];
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"APP*JNT@2015E0298TR", @"authCode", [NSNumber numberWithInteger:model.id], @"id", nil];
        [self requestSubCompanyDataWithUrlString:@"http://118.186.223.151:8050/JBaas/unit/findChildById" parameter:dict];
    }
    
}
#pragma mark - -------数据-------
//汉字转拼音，截取首字母并大写
- (NSString *)transformCharacter:(NSString *)sourceStr {
    NSMutableString *ms = [NSMutableString stringWithString:sourceStr];
    if (ms.length != 0) {
        //将汉字转换为拼音
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformToLatin, NO);
        //将拼音的声调去掉
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO);
        //将字符串所有的字母大写
        NSString *upStr = [ms uppercaseString];
        //首字母截取
        NSString *firstStr = [upStr substringToIndex:1];
        return firstStr;
    }
    return @"#";
}
//排序
- (void)sortAllKeys : (NSArray *)array{
    self.sectionKeysArray = [[NSMutableArray alloc] initWithArray:array];
    for (int i = 0; i < self.sectionKeysArray.count; i++) {
        for (int j = 0; j < self.sectionKeysArray.count - i - 1; j++) {
            if ([self.sectionKeysArray[j] compare:self.sectionKeysArray[j+1]] > 0) {
                [self.sectionKeysArray exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
}

//转换为model
- (void)dicTransformToModelWithDic:(NSDictionary *)dic {
    
    for (NSString *key in _sectionKeysArray) {
        
        NSMutableArray *sectionArray = [[NSMutableArray alloc] init];
        NSArray *smallArray = [self.allDataDic objectForKey:key];
        for (int i = 0; i < smallArray.count; i++) {
            NSDictionary *userInfoDic = [smallArray objectAtIndex:i];
            UserInfoModel *userInfoM = [[UserInfoModel alloc] init];
            [userInfoM setValuesForKeysWithDictionary:userInfoDic];
            [sectionArray addObject:userInfoM];
        }
        [self.allModelDic setObject:sectionArray forKey:key];
    }
}
#pragma mark - -------搜索框-------
//- (UIView *)setSearchView {
//    
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-100, 40)];
//    
//    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(20, 0, view.frame.size.width-40, 25)];
//    self.textFiled.placeholder = @"姓名、工号、电话、手机";
//    [view addSubview:self.textFiled];
//    self.textFiled.delegate =self;
//    
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, view.frame.size.height-10, view.frame.size.width-80, 1)];
//    label.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
//    [view addSubview:label];
//    
//    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, view.frame.size.height-1, self.view.frame.size.width, 1)];
//    lineLabel.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.3];
//    [view addSubview:lineLabel];
//    
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [btn setFrame:CGRectMake(view.frame.size.width-50, 0, 40, 40)];
//    [btn addTarget:self action:@selector(searchBtn:) forControlEvents:UIControlEventTouchUpInside];
//    [btn setImage:[UIImage imageNamed:@"title_btn_search_s.png"] forState:UIControlStateNormal];
//    [view addSubview:btn];
//    
//    return view;
//}
#pragma mark --请求数据--
- (void)fenchDataSourceWithUrlString:(NSString *)urlStr parameter:(NSMutableDictionary *)parameter {
    [self.allDataDic removeAllObjects];
    [JNTDataRequestTools postFetchDataWithUrlString:urlStr paramenters:parameter success:^(id data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *array = dic[@"items"];
        for (int i = 0; i < array.count; i++) {
            //先从临时数组中将字典取出
            NSDictionary *userInfoDic = [array objectAtIndex:i];
            //取出联系人姓名
            NSString *nameStr = [userInfoDic objectForKey:@"name"];
            NSString *upFirstStr = [self transformCharacter:nameStr];
            NSMutableArray *array = [self.allDataDic objectForKey:upFirstStr];
            if (array) {
                [array addObject:userInfoDic];
            }else {
                array = [[NSMutableArray alloc] initWithObjects:userInfoDic, nil];
                [self.allDataDic setObject:array forKey:upFirstStr];
            }
        }
        //排序
        [self sortAllKeys:self.allDataDic.allKeys];
        //model存储
        [self dicTransformToModelWithDic:self.allDataDic];
        [self.tableView reloadData];
    } fail:^{
        NSLog(@"通讯录请求失败");
    } view:self.tableView];
    
}
- (void)requestSubCompanyDataWithUrlString: (NSString *)urlStr parameter:(NSMutableDictionary *)parameter{
    
    [JNTDataRequestTools postFetchDataWithUrlString:urlStr paramenters:parameter success:^(id data) {
        NSDictionary *allDataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *itemsArray = allDataDict[@"items"];
        self.allCompanyArray = [[NSMutableArray alloc] init];
        for (NSDictionary *dict in itemsArray) {
            CompanyModel *model = [[CompanyModel alloc] initWithDictionary:dict error:nil];
            [self.allCompanyArray addObject:model];
        }
        [self.tableView reloadData];
    } fail:^{
        
    } view:self.tableView];
}
- (void)requestSuperCompanyDataWithUrlString: (NSString *)urlStr parameter:(NSMutableDictionary *)parameter{
    [JNTDataRequestTools postFetchDataWithUrlString:urlStr paramenters:parameter success:^(id data) {
        self.topCompanyArray = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *itemsArray = [dict objectForKey:@"items"];
        for (NSDictionary *dict in itemsArray) {
            CompanyModel *companyModel = [[CompanyModel alloc] initWithDictionary:dict error:nil];
            [self.topCompanyArray addObject:companyModel];
        }
        [self initWithButtonInScrollView:self.topCompanyArray];
        [self requestMyCompanyContactData];
    } fail:^{
        
    } view:self.tableView];
}
//搜索按钮回调
//- (void)searchBtn:(UIButton *)sender {
////    NSLog(@"sdfsdgdfgfd");
//    if (self.searchBar.text.length != 0) {
//        NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.textFiled.text,@"name",nil];
//        [self.allModelDic removeAllObjects];
//        [self.sectionKeysArray removeAllObjects];
//        //[self.tableView reloadData];
//        [self fenchDataSourceWithUrlString:AddressBookSearch_URL  parameter:mdic];
//        //        JNTSearchTableViewController *searchVC = [[JNTSearchTableViewController alloc] init];
//        //        searchVC.searchStr = self.textFiled.text;
//        //        [self.navigationController pushViewController:searchVC animated:NO];
//        
//    }else {
//        NSLog(@"输入信息不能为空");
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - -------laying-------
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, kScreenHeight - 70 - 49 - 64)];
        [_tableView registerNib:[UINib nibWithNibName:@"UserListTableViewCell" bundle:nil] forCellReuseIdentifier:@"UserListCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CompanyContactTableViewCell" bundle:nil] forCellReuseIdentifier:@"CompanyContactTableViewCell"];
        _tableView.bounces = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
//- (UITableView *)companyTableView{
//    if (!_companyTableView) {
//        _companyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, kScreenHeight - 70 - 49 - 64) style:UITableViewStylePlain];
//        _companyTableView.bounces = NO;
//        _companyTableView.delegate = self;
//        _companyTableView.dataSource = self;
//        [_companyTableView registerNib:[UINib nibWithNibName:@"CompanyContactTableViewCell" bundle:nil] forCellReuseIdentifier:@"CompanyContactTableViewCell"];
//    }
//    return _companyTableView;
//}
- (NSMutableArray *)sectionKeysArray {
    
    if (!_sectionKeysArray) {
        
        _sectionKeysArray = [[NSMutableArray alloc] init];
    }
    return _sectionKeysArray;
}

- (NSMutableDictionary *) allModelDic {
    
    if (!_allModelDic) {
        
        _allModelDic = [[NSMutableDictionary alloc] init];
    }
    return _allModelDic;
}

- (NSMutableDictionary *)allDataDic {
    
    if (!_allDataDic) {
        
        _allDataDic = [[NSMutableDictionary alloc]init];
    }
    return _allDataDic;
}
- (NSMutableArray *)topCompanyArray{
    if (!_topCompanyArray) {
        _topCompanyArray = [[NSMutableArray alloc] init];
    }
    return _topCompanyArray;
}

//- (AddressSelectedToolsView*)selectedTools {
//    
//    if (!_selectedTools) {
//        
//        NSArray *ar = @[@"集团公司",@"股份公司",@"股份公司",@"智慧城市工程研究所"];
//        _selectedTools = [[AddressSelectedToolsView alloc] initLHSelectedNavigationViewToolsWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80) ButtonTitle:ar searchView:[self setSearchView]];
//        _selectedTools.delegate = self;
//    }
//    return _selectedTools;
//}
// 我的公司
- (void)myCompanyBtnAction: (UIButton *)sender{
    self.isContactCell = YES;
    [self requestMyCompanyContactData];
}




@end
